<template>
  <div class="add-role">
    <!-- 头部导航 -->
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()">
          <i class="el-icon-arrow-left" />返回
        </span>
        <span>|</span>
        <span>{{ roleId ? '编辑角色' : '添加角色' }}</span>
      </div>
      <div class="right">黑马程序员</div>
    </header>
    <!-- 主干 -->
    <main class="add-main">
      <!-- 左侧进度条 -->
      <div class="step-container">
        <el-steps direction="vertical" :active="step">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <!-- 右侧信息表 -->
      <div v-show="step === 1" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form
            ref="form"
            class="form-box"
            :model="roleForm"
            :rules="roleRules"
          >
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleForm.roleName" />
            </el-form-item>
            <el-form-item label="角色描述" prop="remark">
              <el-input v-model="roleForm.remark" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div v-show="step === 2" class="form-container">
        <div class="title">权限配置</div>
        <div class="tree-wrapper">
          <div v-for="item in treeList" :key="item.id" class="tree-item">
            <div class="tree-title">{{ item.title }}</div>
            <!-- show-checkbox：出现复选框 -->
            <!-- default-expand-all：默认展开树形 -->
            <!-- check-strictly：是否绑定复选框父子间的关系，默认为false -->
            <!-- node-key：与每一节点绑定，值应为data（即item.children）里每一项的唯一标识 -->
            <!-- highlight-current：是否高亮当前选中节点 -->
            <el-tree
              ref="tree"
              :data="item.children"
              show-checkbox
              default-expand-all
              check-strictly
              node-key="id"
              :props="{ label: 'title' }"
            />
          </div>
        </div>
      </div>
      <div v-show="step === 3" class="form-container">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
            <div class="form-item">角色描述：{{ roleForm.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div v-for="item in treeList" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>
                <!-- :highlight-current="false" -->
                <el-tree
                  ref="diabledTree"
                  :data="item.children"
                  show-checkbox
                  check-strictly
                  default-expand-all
                  node-key="id"
                  :props="{ label: 'title', disabled: () => true }"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <!-- 底部 -->
    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-show="step != 1" @click="prev">上一步</el-button>
        <el-button v-show="step != 3" type="primary" @click="next">
          下一步
        </el-button>
        <el-button v-show="step === 3" type="primary" @click="submit">
          确认添加
        </el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import {
  getTreeListAPI,
  addRoleAPI,
  rightDetailAPI,
  editRoleAPI
} from '@/api/system'
export default {
  name: 'AddRole',
  data () {
    return {
      step: 1,
      roleForm: { roleName: '123', remark: '123' },
      roleRules: {
        roleName: [
          { required: true, message: '角色名称必填', trigger: 'blur' }
        ],
        remark: [{ required: true, message: '角色描述必填', trigger: 'blur' }]
      },
      treeList: [],
      perms: [] // 获取第2步选中的节点
    }
  },
  computed: {
    roleId () {
      return this.$route.query.roleId
    }
  },
  created () {
    this.getTreeList()
    if (this.roleId) {
      this.rightDetail()
    }
  },
  methods: {
    // 上一步
    prev () {
      if (this.step > 1) {
        this.step--
      }
    },
    // 下一步
    next () {
      if (this.step < 3) {
        if (this.step === 1) {
          // 校验表单
          this.$refs.form.validate(flag => {
            if (!flag) return
            this.step++
          })
        } else if (this.step === 2) {
          this.perms = []
          // 获取选中节点有2种方式，node和key
          this.$refs.tree.forEach(ele => {
            // node获取的是data（即children）里的每一项组成的数组（由于每一项是个完整的对象，包含id和title，所以整体是个对象数组）
            // console.log(ele.getCheckedNodes())
            // key获取的是由node-key绑定的数据（即children里的id）组成的数组
            // console.log(ele.getCheckedKeys())
            // 由于接口只要id数据，所以这里用key方式（getCheckedKeys）
            this.perms.push(ele.getCheckedKeys())
          })
          // console.log(this.perms.flat()) // flat方法会将多维数组展开，默认（无参数）只展开一层
          if (this.perms.flat().length) {
            // []为true，''为false'，0为false
            this.step++
            // 在进入第3步之前回显步骤3的选中项（也可以在进入第3步以后进行这个操作）
            this.$refs.diabledTree.forEach((item, index) => {
              item.setCheckedKeys(this.perms[index])
            })
          } else {
            this.$message.warning('配置权限不得为空')
            return
          }
        }
      }
    },
    // 查询所有功能权限(树形)
    async getTreeList () {
      const res = await getTreeListAPI()
      // console.log('所有功能权限(树形)', res)
      this.treeList = res.data
    },
    // 提交（添加和编辑）
    async submit () {
      if (this.roleId) {
        const res = await editRoleAPI({
          ...this.roleForm,
          roleId: this.roleId,
          perms: this.perms
        })
        console.log('编辑角色', res)
        this.$message.success('修改成功')
      } else {
        // console.log({ ...this.roleForm, perms: this.perms })
        const res = await addRoleAPI({
          ...this.roleForm,
          perms: this.perms
        })
        console.log('添加角色', res)
        this.$message.success('添加成功')
      }
      this.$router.back()
    },
    // 查询当前角色详情-权限和分配人数
    async rightDetail () {
      const res = await rightDetailAPI(this.roleId)
      console.log('哪些权限打钩', res)
      this.roleForm.roleName = res.data.roleName
      this.roleForm.remark = res.data.remark
      this.perms = res.data.perms
      console.log(this.perms)
      const trees = this.$refs.tree
      console.log(trees)
      trees.forEach((ele, index) => {
        ele.setCheckedKeys(this.perms[index]) // 回显权限打钩
      })
    }
  }
}
</script>
<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 230px;
    display: flex;
    .step-container {
      height: 400px;
      width: 200px;
    }
    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
        }
        .info {
          font-size: 14px;
          color: #666;
          .form-item {
            margin-bottom: 20px;
          }
        }
      }
      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }
  .tree-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .tree-item {
      flex: 1;
      padding: 0px 4px;
      text-align: center;
      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>
